package com.ruoyi.project.system.controller;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.aspectj.lang.annotation.Anonymous;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.interceptor.annotation.RepeatSubmit;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.domain.DtRecharge;
import com.ruoyi.project.system.domain.SysRole;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.domain.vo.Commission;
import com.ruoyi.project.system.mapper.DtProductMapper;
import com.ruoyi.project.system.mapper.SysNoticeMapper;
import com.ruoyi.project.system.mapper.SysUserMapper;
import com.ruoyi.project.system.service.IDtFinalResultService;
import com.ruoyi.project.system.service.ISysRoleService;
import com.ruoyi.project.system.service.ISysUserService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static com.ruoyi.common.constant.CacheConstants.DT_RUN_XYHS;

/**
 * 用户信息
 */
@RestController
@RequestMapping("/user")
public class SysUserController extends BaseController {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private IDtFinalResultService idfrs;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysNoticeMapper sysNoticeMapper;

    @Autowired
    private DtProductMapper dtProductMapper;

    @Autowired
    public RedisCache rc;

    @GetMapping("/index")
    public AjaxResult index() {
        Long userId = SecurityUtils.getUserId();
        Map aj = new HashMap<String, Object>();
        aj.put("balance", sysUserMapper.queryBalanceByUserId(userId, false));
        aj.put("commission", sysUserMapper.commission(userId));
        aj.put("statistics", idfrs.statistics(userId));
        aj.put("notice", sysNoticeMapper.newNotice());
        if (SecurityUtils.isAdmin()) {
            BigDecimal sjcz = rc.getCacheObject(DT_RUN_XYHS + "sjcz");
            BigDecimal yjff = rc.getCacheObject(DT_RUN_XYHS + "yjff");
            BigDecimal jkfy = rc.getCacheObject(DT_RUN_XYHS + "jkfy");
            Map<String, Object> hs = new HashMap<>();
            hs.put("sjcz", sjcz.floatValue());
            hs.put("yjff", yjff.floatValue());
            hs.put("jkfy", jkfy.floatValue());
            hs.put("hs", sjcz.subtract(yjff).subtract(jkfy));
            aj.put("stat", hs);
        }
        return success(aj);
    }

    @GetMapping("/fastQuery/{ui}")
    public AjaxResult fastQuery(@PathVariable("ui") Long userId) {
        if (SecurityUtils.isAdmin() || userId.longValue() == SecurityUtils.getUserId().longValue()) {
            SysUser sysUser = sysUserMapper.selectUserById(userId);
            AjaxResult result = new AjaxResult();
            result.put("command", sysUser.getCommand());
            result.put("identityCode", sysUser.getIdentityCode());
            return result;
        } else {
            return error();
        }
    }

    @Anonymous
    @GetMapping("/icVerification/{ic}")
    public AjaxResult icVerification(@PathVariable String ic) {
        Long userId = sysUserMapper.queryUserIdByCommand(ic);
        if (userId == null) {
            return warn("链接异常！");
        }
        return success(dtProductMapper.queryEnableProductList(userId, "query"));
    }

    @RepeatSubmit
    @GetMapping("/addQA")
    public AjaxResult addQA(@NotBlank String question) {
        Long userId = SecurityUtils.getUserId();
        return success(sysUserMapper.insertDtQA(userId, question));
    }

    @GetMapping("/commission")
    public AjaxResult commission(@NotNull Long userId) {
        return success(sysUserMapper.commission(userId));
    }


    @PutMapping("/command")
    public AjaxResult command(@NotBlank String command) {
        Long userId = SecurityUtils.getUserId();
        return success(sysUserMapper.setCommand(userId, command));
    }

    /**
     * 获取余额
     */
    @GetMapping("/balance")
    public AjaxResult balance() {
        return success(sysUserMapper.queryBalanceByUserId(SecurityUtils.getUserId(), false));
    }

    @PreAuthorize("@ss.hasPermi('system:user:recharge')")
    @GetMapping("/sysRecharge")
    public AjaxResult sysRecharge(@NotNull Long userId, @NotNull BigDecimal amount) {
        if (amount.floatValue() < 0.0f) {
            return warn("金额异常");
        }
        DtRecharge dtRecharge = new DtRecharge(userId, "人工", amount, "ENABLE");
        int i = userService.sysRecharge(userId, amount, dtRecharge);
        rc.setIncrement(DT_RUN_XYHS + "sjcz", amount.doubleValue());
        Long parentId = sysUserMapper.queryParentByUserId(userId);
        if (parentId != null) {
            Commission commission = sysUserMapper.commission(parentId);
            if (commission != null && !"OFF".equals(commission.getCommissionType())) {  // 上级要充值
                BigDecimal commissionAmount = amount.multiply(new BigDecimal(commission.getCommissionRate()));
                String ct = commission.getCommissionType();
                userService.sysRecharge(
                        parentId,
                        commissionAmount,
                        new DtRecharge(parentId, "佣金", commissionAmount, "CASH".equals(ct) ? "CREATE_NO_GRANT" : "ENABLE", "source：" + dtRecharge.getId())
                );
            }
        }
        return toAjax(i);
    }

    @RepeatSubmit
    @PreAuthorize("@ss.hasPermi('system:user:recharge')")
    @GetMapping("/parentRecharge")
    public AjaxResult parentRecharge(@NotNull Long rechargeUserId, @NotNull BigDecimal amount) {
        if (amount.floatValue() < 0.0f) {
            return error("金额异常");
        }
        Long userId = SecurityUtils.getUserId();
        if (userId.longValue() != sysUserMapper.queryParentByUserId(rechargeUserId).intValue()) {
            return error("没有上下级关系");
        }
        BigDecimal balance = sysUserMapper.queryBalanceByUserId(userId, true);
        if (balance.floatValue() < 0.0f) {
            return warn("您的余额不足，请充值！");
        } else if (balance.compareTo(amount) < 0) {
            return warn("分配金额超出您的余额，请充值您的余额！");
        }
        sysUserMapper.subtractBalance(userId, amount);
        return toAjax(userService.sysRecharge(
                rechargeUserId,
                amount,
                new DtRecharge(rechargeUserId, "分配", amount, "ENABLE", " 分配充值（" + userId + "）"))
        );
    }

    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:listByParent')")
    @GetMapping("/listByParent")
    public Object listByParent(SysUser user) {
        user.setParent(SecurityUtils.getUserId());
        if (user.getParent() == null) {
            return error("缺少参数");
        }
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = {"/", "/{userId}"})
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        userService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));

        if (StringUtils.isNotNull(userId)) {
            SysUser sysUser = userService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        roleService.checkRoleDataScope(user.getRoleId());
        if (!userService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        roleService.checkRoleDataScope(user.getRoleId());
        if (!userService.checkUserNameUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, getUserId())) {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(userService.selectUserById(user.getUserId()));
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUser(user));
    }

}

